package com.canbot.u05.activity.guide;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.guide.MapInfo;
import com.canbot.u05.bean.guide.MapMsgBean;
import com.canbot.u05.bean.guide.MapTaskInfo;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.helper.DialogBuildHelper;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

/**
 * @author zmp
 * 导览模式首界面
 */
public class GuideActivity extends BaseActivityNoTitle {

        private View mainView;

        private ToastTools toastTools;

        private MyAdapter myAdapter;

        private String currentMapName = "";

        public static MapInfo mMapInfo;

        private List<MapTaskInfo> mTaskInfos;

        private TextView guideTitle;

        private String newName;

        private static final int CHANGE_MAP_CODE = 101;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                setContentView(R.layout.activity_guide);
                initViews();
                toastTools = ToastTools.newInstance(this);
                initData();
        }

        private void initViews() {
                mainView = findViewById(R.id.main_iv);
                ListView mListView = (ListView) findViewById(R.id.guide_lv);
                guideTitle = (TextView) findViewById(R.id.main_tv);
                findViewById(R.id.guide_add_task).setOnClickListener(popClickListener);
                findViewById(R.id.main_change_bt).setOnClickListener(popClickListener);
                myAdapter = new MyAdapter();
                mListView.setAdapter(myAdapter);
                mListView.setOnItemClickListener(onItemClickListener);
        }

        private void initData() {
                showLoadDialog();
                getMapInfo(false);
        }

        @Override
        protected void onResume() {
                super.onResume();
                EventBus.getDefault().register(this);
                myAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPause() {
                super.onPause();
                EventBus.getDefault().unregister(this);
        }

        /**
         * 消息发布者位置
         * ReceiveData
         * mHandler
         * case MsgType.MOBILE_PAD_MAP_TASK:
         *
         * @param bean
         */
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMapEvent(StringMsgBean bean) {
                if (bean.getMsgType() == MsgType.MOBILE_PAD_MAP_TASK) {
                        String msgData = bean.getMsgData();
                        if (!TextUtils.isEmpty(msgData)) {
                                loadDialog.dismiss();
                                MapMsgBean mapMsgBean = new Gson().fromJson(msgData, MapMsgBean.class);
                                if (MapMsgBean.MOBILE_RENAME_TASK == mapMsgBean.getMsgType()) {
                                        if (mapMsgBean.isSuccess()) {
                                                mTaskInfos.get(position).setTaskName(newName);
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                myAdapter.notifyDataSetChanged();
                                                        }
                                                });
                                        } else {
                                                toastTools.showText(getString(R.string.service_error_hint));
                                        }
                                } else {
                                        if (MapMsgBean.MOBILE_DELETE_TASK == mapMsgBean.getMsgType()) {
                                                if (mapMsgBean.isSuccess()) {
                                                        runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                        mTaskInfos.remove(position);
                                                                        myAdapter.notifyDataSetChanged();
                                                                }
                                                        });
                                                } else {
                                                        loadDialog.dismiss();
                                                        toastTools.showText(getString(R.string.service_error_hint));
                                                }
                                        }
                                }
                        }
                }
        }

        /**
         * listView item click
         */
        private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(GuideActivity.this, GuideMapAddTaskActivity.class);
                        intent.putExtra(GuideMapAddTaskActivity.TASK_DATA_KEY, position);
                        intent.putExtra(GuideMapAddTaskActivity.TASK_DATA, JSON.toJSONString(mMapInfo.getMapTaskInfos().get(position)));
                        startOtherActivity(intent, false);
                }
        };

        public void back(View view) {
                Log.d("View", " back ");
                finish();
        }

        /**
         * 提示Dialog
         */
        private DialogBuildHelper.TipBuilder hintDialog;

        /**
         * 更名Dialog
         */
        private DialogBuildHelper.SetNameTipBuilder renameDialog;

        /**
         * 删除Dialog
         */
        private DialogBuildHelper.TipBuilder deleteDialog;

        /**
         * 提示Dialog
         */
        private void showHintDialog() {
                if (hintDialog == null) {
                        hintDialog = DialogBuildHelper.createDialogTip(this)
                                .setCancelable(false)
                                .setClickListener(new DialogBuildHelper.ITipClickListener() {

                                        @Override
                                        public void sure() {
                                                startForResultActivity(GuideMapListActivity.class, CHANGE_MAP_CODE);
                                        }
                                }, true);
                }
                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(0));
                String format = String.format(getString(R.string.guide_map_hint), currentMapName);
                hintDialog.setContent(format, Gravity.START);
        }

        /**
         * 删除Dialog
         */
        private void showDeleteDialog() {
                if (deleteDialog == null) {
                        deleteDialog = DialogBuildHelper.createDialogTip(this)
                                .setCancelable(false).setContent("是否删除该任务?", Gravity.CENTER)
                                .setClickListener(new DialogBuildHelper.ITipClickListener() {
                                        @Override
                                        public void sure() {
                                                loadDialog.show();
                                                deleteTask(mTaskInfos.get(position).get_id());
                                        }
                                }, true);
                }
                deleteDialog.show();
        }

        /**
         * 提示Dialog
         */
        private void showRenameDialog() {
                if (renameDialog == null) {
                        renameDialog = DialogBuildHelper.createDialogSetName(this)
                                .setCancelable(false)
                                .setTitle(getString(R.string.task_renaming))
                                .setClickListener(new DialogBuildHelper.ISetNameClickListener() {
                                        @Override
                                        public void sure(String text, TextView tipTextView) {
                                                if (TextUtils.isEmpty(text)) {
                                                        toastTools.showText(getString(R.string.mapname_cannot_empty));
                                                        tipTextView.setText(getString(R.string.mapname_cannot_empty));
                                                        return;
                                                }
                                                if (!text.matches("[\\u4E00-\\u9FA5A-Za-z0-9]+")) {
                                                        toastTools.showText(getString(R.string.contains_illegal_characters));
                                                        tipTextView.setText(getString(R.string.contains_illegal_characters));
                                                        return;
                                                }
                                                for (MapTaskInfo mTaskInfo : mTaskInfos) {
                                                        if (text.equals(mTaskInfo.getTaskName())) {
                                                                toastTools.showText(getString(R.string.mapname_already_exists));
                                                                tipTextView.setText(getString(R.string.mapname_already_exists));
                                                                return;
                                                        }
                                                }
                                                renameDialog.dismiss();
                                                showLoadDialog();
                                                reNameTask(mTaskInfos.get(position).get_id(), text);
                                        }

                                }, false);
                }
                renameDialog.setContent(mTaskInfos.get(position).getTaskName()).show();
        }

        private int position;

        private PopupWindow popupWindow;


        /**
         * popwindow点击事件 and dialog点击事件
         */
        OnClickListener popClickListener = new OnClickListener() {
                @Override
                public void onClick(View view) {
                        switch (view.getId()) {
                                case R.id.guide_add_task:
                                        Intent intent = new Intent(GuideActivity.this, GuideMapAddTaskActivity.class);
                                        intent.putExtra(GuideMapAddTaskActivity.TASK_DATA_KEY, -1);
                                        startOtherActivity(intent, false);
                                        MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(2));
                                        break;
                                case R.id.main_change_bt:
                                        startForResultActivity(GuideMapListActivity.class, CHANGE_MAP_CODE);
                                        break;
                                case R.id.guide_pop_item_r1:
                                        popupWindow.dismiss();
                                        showLoadDialog();
                                        runTask(mTaskInfos.get(position).getTaskName());
                                        break;
                                case R.id.guide_pop_item_r2:
                                        popupWindow.dismiss();
                                        showRenameDialog();
                                        break;
                                case R.id.guide_pop_item_r3:
                                        popupWindow.dismiss();
                                        showDeleteDialog();
                                        break;
                                default:

                        }
                }
        };


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == CHANGE_MAP_CODE) {
                        if (resultCode == RESULT_OK) {
                                showLoadDialog();
                                getMapInfo(true);
                        } else if (resultCode == RESULT_CANCELED){
                               finish();
                        }
                }
        }

        private class MyAdapter extends BaseAdapter implements OnClickListener {


                @Override
                public int getCount() {
                        return mTaskInfos == null || mTaskInfos.size() == 0 ? 0 : mTaskInfos.size();
                }

                @Override
                public Object getItem(int position) {
                        return mTaskInfos.get(position);
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        Holder holder;
                        if (convertView == null) {
                                convertView = View.inflate(GuideActivity.this, R.layout.guide_list_item, null);
                                holder = new Holder(convertView);
                                convertView.setTag(holder);
                        }
                        holder = (Holder) convertView.getTag();
                        holder.textView.setText(mTaskInfos.get(position).getTaskName());
                        holder.viewById.setTag(position);
                        holder.viewById.setOnClickListener(this);
                        return convertView;
                }


                /**
                 * listView item pop点击事件
                 */
                @Override
                public void onClick(View view) {
                        position = ((int) view.getTag());
                        if (popupWindow == null) {
                                View inflate = View.inflate(GuideActivity.this, R.layout.guide_list_item_pop, null);
                                inflate.findViewById(R.id.guide_pop_item_r1).setOnClickListener(popClickListener);
                                inflate.findViewById(R.id.guide_pop_item_r2).setOnClickListener(popClickListener);
                                inflate.findViewById(R.id.guide_pop_item_r3).setOnClickListener(popClickListener);
                                popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                                popupWindow.setOutsideTouchable(true);
                                //设置 popupWindow外面可点击
                                popupWindow.setBackgroundDrawable(new ColorDrawable());
                        }
                        int[] location = new int[2];
                        view.getLocationInWindow(location);
                        Log.e("location", location[0] + "," + location[1]);
                        int height = popupWindow.getContentView().getMeasuredHeight();
                        int width = popupWindow.getContentView().getMeasuredWidth();
                        int mainHeight = mainView.getMeasuredHeight();
                        Log.e("location", height + "==maxAvailableHeight" + mainHeight);
                        popupWindow.showAtLocation(mainView, Gravity.START | Gravity.TOP, location[0] - width, (int) (location[1] - getResources().getDimension(R.dimen.px5)));
                }
        }

        class Holder {

                private TextView textView;

                private View viewById;

                public Holder(View convertView) {
                        textView = (TextView) convertView.findViewById(R.id.guide_item_tv);
                        viewById = convertView.findViewById(R.id.guide_item_bt);
                }
        }


        public static final int MAP_TYPE_GET_TASK_LIST = 0;

        public static final int MAP_TYPE_RENAME_MAP_TASK = 3;

        public static final int MAP_TYPE_DELETE_MAP_TASK = 4;

        public static final int MAP_TYPE_RUN_MAP_TASK = 5;

        public static final int MAP_TYPE_JOP_TYPE = 18;

        @Override
        protected void onDestroy() {
                MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop_sound");
                super.onDestroy();
        }

        private void getMapInfo(final boolean isLoad) {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", MAP_TYPE_GET_TASK_LIST + "");
                hashMap.put("data", 1);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                                if (TextUtils.isEmpty(result)) {
                                        startForResultActivity(GuideMapListActivity.class, CHANGE_MAP_CODE);
                                        loadDialog.dismiss();
                                        return;
                                }
                                mMapInfo = new Gson().fromJson(result, MapInfo.class);
                                mTaskInfos = mMapInfo.getMapTaskInfos();
                                Log.e("TTS2Voice", mTaskInfos + "");
                                Log.e("TTS2Voice", mMapInfo.getLocalPoints() + "");
                                currentMapName = mMapInfo.getMapName();
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                String format = String.format(getString(R.string.guide_current_map), currentMapName);
                                                guideTitle.setText(format);
                                                loadDialog.dismiss();
                                                myAdapter.notifyDataSetChanged();
                                                if (!isLoad) {
                                                        showHintDialog();
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText(getString(R.string.service_error_hint));
                                finish();
                        }
                });
        }


        private void reNameTask(long taskID, String newName) {
                this.newName = newName;
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", MAP_TYPE_RENAME_MAP_TASK + "");
                hashMap.put("data", taskID + ":" + newName);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                });
        }

        private void deleteTask(long taskID) {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", MAP_TYPE_DELETE_MAP_TASK + "");
                hashMap.put("data", taskID);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                                loadDialog.setCancelable(true);
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                });
        }

        private void runTask(final String taskName) {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", MAP_TYPE_RUN_MAP_TASK + "");
                hashMap.put("data", taskName);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                                loadDialog.dismiss();
                                if ("success".equals(result)) {
                                        Intent intent = new Intent(GuideActivity.this, GuideMapTaskRunningActivity.class);
                                        intent.putExtra("taskName", taskName);
                                        startOtherActivity(intent, false);
                                } else {
                                        toastTools.showText(getString(R.string.mission_execution_failed));
                                }
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                });
        }

        //        private void saveMapJop(final String jopName) {
        //                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
        //                HashMap<String, Object> hashMap = new HashMap<>();
        //                hashMap.put("type", MAP_TYPE_JOP_TYPE);
        //                hashMap.put("data", jopName);
        //                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
        //                        @Override
        //                        public void onSuccess(String result) {
        //                                Log.e("TTS2Voice", result);
        //                                loadDialog.dismiss();
        //                                if ("success".equals(result)) {
        //                                        mCurrentJopPosition = mJopPosition;
        //                                        runOnUiThread(new Runnable() {
        //                                                @Override
        //                                                public void run() {
        //                                                        jopTv.setText(jopName);
        //                                                }
        //                                        });
        //                                }
        //                                else {
        //                                        toastTools.showText(getString(R.string.failed_set_post));
        //                                }
        //                                if (mTaskInfos == null || mTaskInfos.size() == 0) {
        //                                        MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList
        // .get(1));
        //                                }
        //                        }
        //
        //                        @Override
        //                        public void onFailure() {
        //                                loadDialog.dismiss();
        //                                toastTools.showText(getString(R.string.service_error_hint));
        //                        }
        //                });
        //        }


        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        loadDialog.setCancelable(false);
                }
                StatusBarUtil.hideVirtualKey(loadDialog);
                loadDialog.show();
        }
}
